/* Copyright 2008. All rights reserved. */
package org.bling.parser.tags;

import org.bling.parser.BlingParserException;
import org.bling.process.events.EventProcessor;
import org.bling.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Widget;

/**
 * renders an SWT MenuItem, to be used inside of a Menu
 * 
 * @author DISBROB
 * 
 */
public class MenuItemTag extends Tag {

	protected MenuItem menuItem;
	protected String onSelect = "";

	public void setOnSelect(String onSelect) {
		this.onSelect = onSelect;
	}

	@Override
	public int doStartTag() throws BlingParserException {
		super.doStartTag();

		if (!(parent.getWidget() instanceof Menu)) {
			throw new BlingParserException("Invalid location of Menu Item tag.");
		}

		Menu parentMenu = (Menu) parent.getWidget();

		// FIXME: This should be SWT.PUSH if it does not have a sub menu, right?
		menuItem = new MenuItem(parentMenu, SWT.CASCADE);

		return EVAL_PAGE;
	}

	@Override
	public int doAfterBody() throws BlingParserException {
		super.doAfterBody();

		if (Util.isBlankOrNull(bodyContent) && menuItem.getMenu() == null) {
			Menu parentMenu = (Menu) parent.getWidget();
			menuItem.dispose();
			menuItem = new MenuItem(parentMenu, SWT.SEPARATOR);
		}

		if (!Util.isBlankOrNull(bodyContent)) {
			menuItem.setText(bodyContent);
		}

		// FIXME: keyboard shortcuts menuItem.setAccelerator(SWT.CTRL + 'x');

		if (!onSelect.equals("")) {
			menuItem.addSelectionListener(new EventProcessor(onSelect));
		}

		return EVAL_PAGE;
	}

	@Override
	public Widget getWidget() throws BlingParserException {
		return menuItem;
	}

}
